
import { getExpenses, delExpense, getStatisticalAggregate } from '../../api/expense'
const app = getApp();
const cur_date = new Date()
Page({
  data: {
    result: {},
    expenses: [],
    cur_date: [2022, 4],
    query: {
      page: 1,
      date: '2022-4'
    },
    income_sum: 0,
    spending_sum: 0
  },
  onLoad(options) {
    if (options.from === 'add') {
      // 创建成功，提示
      wx.showToast({
        title: '添加成功',
        icon: 'none'
      })
    } else {
      // 加载数据
      wx.showLoading({ title: '加载中', mask: true })
    }
    this._getUserInfo().then(res=>{
      this._fetchData(this.data.query).then(res => {

      }).finally(() => wx.hideLoading())
    }).finally(() => wx.hideLoading())
    // console.log(this.data.query)s
  },
  _getUserInfo: function () {
    return app.getUserInfo(false).then(userInfo => {
      if (userInfo.nickname != 'Demo') {
        this.setData({
          cur_date: [cur_date.getFullYear(), cur_date.getMonth() + 1],
          'query.date': `${cur_date.getFullYear()}-${cur_date.getMonth() + 1}`,
        })
      }
    })
  },
  // 日期选择查询
  DateChange(e) {
    const date = e.detail.value
    this.setData({
      [`query.date`]: date,
      cur_date: date.split('-'),
      expenses: []
    })
    wx.showLoading({ title: '加载中', mask: true })
    this._fetchData(this.data.query).then(res => {

    }).finally(() => wx.hideLoading())

  },
  _fetchData: function (query) {
    getStatisticalAggregate({ date: this.data.query.date }).then(res => {
      // 支出 收入总和
      this.setData({
        spending_sum: res.data.spending_sum,
        income_sum: res.data.income_sum,
      })
    })
    return getExpenses(query).then(res => {
      this.setData({
        result: res.data,  // 记录分页等查询信息
        expenses: this.data.expenses.concat(res.data.results),
      })
      return res.data.results
    }).catch(() => {
      return []
    })
  },
  delExpenseTap: function (e) {
    // 删除
    const that = this
    const { group, id, index } = e.target.dataset
    this.setData({
      modalName: null
    })
    delExpense(id).then(res => {

      if (that.data.expenses[group].expenses.length === 1) {
        // 分组只剩下一个账单, 移除掉整个分组
        that.data.expenses.splice(group, 1)
      } else {
        that.data.expenses[group].expenses.splice(index, 1)
      }

      setTimeout(function () {   // 延时操作
        wx.showToast({
          title: '删除成功',
          icon: 'none'
        })
        that.setData({
          expenses: that.data.expenses
        })
      }, 400);
    })
  },

  /**
 * 页面上拉触底事件的处理函数
 */
  onReachBottom: function () {
    let { query, result } = this.data
    if (result.has_next) {
      query['page'] = result.next
      this._fetchData(query).then(res => {
        console.log(res)
      }).catch(() => this.setData({ loadMoreStatus: 'hidding' }))
    }
  },
  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },
})